// image.js
// 初始化图片调整大小功能
function initImageResizing() {
    const editor = document.getElementById('editor');

    // 监听图片插入
    editor.addEventListener('input', (e) => {
        const images = editor.getElementsByTagName('img');
        Array.from(images).forEach(img => {
            if (!img.parentElement.classList.contains('image-wrapper')) {
                setupImageWrapper(img);
            }
        });
    });
}

// 设置图片包装器
function setupImageWrapper(img) {
    // 创建图片块容器
    const imageBlock = document.createElement('div');
    imageBlock.className = 'image-block block'; // 添加block类以支持拖动

    const wrapper = document.createElement('div');
    wrapper.className = 'image-wrapper';

    // 创建左侧调整手柄
    const leftHandle = document.createElement('div');
    leftHandle.className = 'image-resize-handle left';

    // 创建右侧调整手柄
    const rightHandle = document.createElement('div');
    rightHandle.className = 'image-resize-handle right';

    // 创建拖动手柄
    const dragHandle = document.createElement('div');
    dragHandle.className = 'block-drag-handle';
    dragHandle.innerHTML = '⋮⋮';
    dragHandle.contentEditable = false;

    // 包装图片
    img.parentNode.insertBefore(imageBlock, img);
    imageBlock.appendChild(dragHandle); // 添加拖动手柄
    imageBlock.appendChild(wrapper);
    wrapper.appendChild(img);
    wrapper.appendChild(leftHandle);
    wrapper.appendChild(rightHandle);

    // 添加调整大小事件
    setupResizeHandlers(wrapper, leftHandle, rightHandle, img);

    // 添加图片复制功能
    setupImageCopyHandler(img, imageBlock);

    // 将普通段落转换为文本块
    convertToBlocks();
}

// 添加图片复制功能
function setupImageCopyHandler(img, imageBlock) {
    // 添加右键菜单
    imageBlock.addEventListener('contextmenu', (e) => {
        e.preventDefault();
        
        // 创建自定义右键菜单
        const menu = document.createElement('div');
        menu.className = 'image-context-menu';
        menu.innerHTML = `
            <div class="menu-item" data-action="copy">复制图片</div>
            <div class="menu-item" data-action="duplicate">复制图片块</div>
        `;
        
        // 定位菜单
        menu.style.left = `${e.pageX}px`;
        menu.style.top = `${e.pageY}px`;
        document.body.appendChild(menu);
        
        // 处理菜单项点击
        menu.addEventListener('click', (event) => {
            const action = event.target.dataset.action;
            
            if (action === 'copy') {
                // 复制图片到剪贴板
                copyImageToClipboard(img);
            } else if (action === 'duplicate') {
                // 复制整个图片块
                duplicateImageBlock(imageBlock);
            }
            
            // 移除菜单
            document.body.removeChild(menu);
        });
        
        // 点击其他地方关闭菜单
        document.addEventListener('click', function closeMenu() {
            if (document.body.contains(menu)) {
                document.body.removeChild(menu);
            }
            document.removeEventListener('click', closeMenu);
        });
    });
    
    // 添加双击复制功能
    imageBlock.addEventListener('dblclick', () => {
        copyImageToClipboard(img);
    });
}

// 复制图片到剪贴板
async function copyImageToClipboard(img) {
    try {
        // 创建一个canvas元素
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 等待图片加载完成
        await new Promise((resolve) => {
            if (img.complete) {
                resolve();
            } else {
                img.onload = resolve;
            }
        });
        
        // 设置canvas大小
        canvas.width = img.naturalWidth;
        canvas.height = img.naturalHeight;
        
        // 在canvas上绘制图片
        ctx.drawImage(img, 0, 0);
        
        // 将canvas转换为blob
        canvas.toBlob(async (blob) => {
            try {
                // 创建ClipboardItem对象
                const item = new ClipboardItem({ 'image/png': blob });
                
                // 写入剪贴板
                await navigator.clipboard.write([item]);
                
                // 显示成功提示
                showToast('图片已复制到剪贴板');
            } catch (err) {
                console.error('复制图片失败:', err);
                showToast('复制图片失败', 'error');
            }
        });
    } catch (err) {
        console.error('处理图片失败:', err);
        showToast('处理图片失败', 'error');
    }
}

// 复制图片块
function duplicateImageBlock(imageBlock) {
    // 克隆图片块
    const newImageBlock = imageBlock.cloneNode(true);
    
    // 确保ID不重复
    newImageBlock.dataset.blockId = Date.now();
    
    // 在原图片块后插入新图片块
    imageBlock.after(newImageBlock);
    
    // 重新绑定事件
    const img = newImageBlock.querySelector('img');
    const wrapper = newImageBlock.querySelector('.image-wrapper');
    const leftHandle = newImageBlock.querySelector('.image-resize-handle.left');
    const rightHandle = newImageBlock.querySelector('.image-resize-handle.right');
    
    // 重新设置调整大小事件
    setupResizeHandlers(wrapper, leftHandle, rightHandle, img);
    
    // 重新设置复制事件
    setupImageCopyHandler(img, newImageBlock);
    
    // 触发自动保存
    if (typeof autoSave === 'function') {
        autoSave();
    }
    
    // 显示成功提示
    showToast('图片块已复制');
}

// 显示提示消息
function showToast(message, type = 'success') {
    // 检查是否已有toast函数
    if (typeof window.appFunctions !== 'undefined' && typeof window.appFunctions.showToast === 'function') {
        window.appFunctions.showToast(message, type);
        return;
    }
    
    // 创建一个简单的toast元素
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    toast.style.position = 'fixed';
    toast.style.bottom = '20px';
    toast.style.right = '20px';
    toast.style.padding = '10px 20px';
    toast.style.backgroundColor = type === 'success' ? '#4caf50' : '#f44336';
    toast.style.color = 'white';
    toast.style.borderRadius = '4px';
    toast.style.zIndex = '1000';
    toast.style.opacity = '0';
    toast.style.transition = 'opacity 0.3s';
    
    document.body.appendChild(toast);
    
    // 显示toast
    setTimeout(() => {
        toast.style.opacity = '1';
    }, 10);
    
    // 自动隐藏
    setTimeout(() => {
        toast.style.opacity = '0';
        setTimeout(() => {
            if (document.body.contains(toast)) {
                document.body.removeChild(toast);
            }
        }, 300);
    }, 3000);
}

// 将编辑器中的普通段落转换为文本块
function convertToBlocks() {
    const editor = document.getElementById('editor');
    const paragraphs = editor.getElementsByTagName('p');

    Array.from(paragraphs).forEach(p => {
        if (!p.classList.contains('text-block')) {
            p.className = 'text-block block';
        }
    });
}

// 修改调整大小处理程序
function setupResizeHandlers(wrapper, leftHandle, rightHandle, img) {
    [leftHandle, rightHandle].forEach(handle => {
        handle.addEventListener('mousedown', (e) => {
            e.preventDefault();

            const startX = e.clientX;
            const startWidth = wrapper.offsetWidth;
            const isLeft = handle.classList.contains('left');
            wrapper.classList.add('resizing');

            function onMouseMove(e) {
                const delta = e.clientX - startX;
                const newWidth = isLeft ? startWidth - delta : startWidth + delta;

                // 限制最小宽度
                if (newWidth >= 50) {
                    wrapper.style.width = `${newWidth}px`;
                }
            }

            function onMouseUp() {
                wrapper.classList.remove('resizing');
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }

            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);
        });
    });
}

// 添加粘贴处理函数
function setupPasteHandler() {
    const editor = document.getElementById('editor');

    editor.addEventListener('paste', async (e) => {
        e.preventDefault();

        const items = (e.clipboardData || window.clipboardData).items;

        for (let item of items) {
            if (item.type.indexOf('image') !== -1) {
                // 处理图片粘贴
                const file = item.getAsFile();
                const reader = new FileReader();

                reader.onload = function(event) {
                    // 创建图片块
                    const imageBlock = document.createElement('div');
                    imageBlock.className = 'image-block block'; // 添加block类以支持拖动
                    imageBlock.dataset.blockId = Date.now(); // 添加唯一ID

                    // 创建拖动手柄
                    const dragHandle = document.createElement('div');
                    dragHandle.className = 'block-drag-handle';
                    dragHandle.innerHTML = '⋮⋮';
                    dragHandle.contentEditable = false;

                    const wrapper = document.createElement('div');
                    wrapper.className = 'image-wrapper';

                    const img = document.createElement('img');
                    img.src = event.target.result;

                    // 创建调整手柄
                    const leftHandle = document.createElement('div');
                    leftHandle.className = 'image-resize-handle left';

                    const rightHandle = document.createElement('div');
                    rightHandle.className = 'image-resize-handle right';

                    // 组装图片块
                    wrapper.appendChild(img);
                    wrapper.appendChild(leftHandle);
                    wrapper.appendChild(rightHandle);
                    imageBlock.appendChild(dragHandle); // 添加拖动手柄
                    imageBlock.appendChild(wrapper);

                    // 获取当前选中的块
                    const selection = window.getSelection();
                    const range = selection.getRangeAt(0);
                    const currentBlock = range.startContainer.closest('.block');

                    // 在当前块后插入图片块
                    if (currentBlock) {
                        currentBlock.after(imageBlock);
                    } else {
                        editor.appendChild(imageBlock);
                    }

                    // 设置调整大小事件
                    setupResizeHandlers(wrapper, leftHandle, rightHandle, img);
                    
                    // 设置图片复制功能
                    setupImageCopyHandler(img, imageBlock);
                    
                    // 触发自动保存
                    if (typeof autoSave === 'function') {
                        autoSave();
                    }
                };

                reader.readAsDataURL(file);
            } else if (item.type === 'text/plain') {
                // 处理文本粘贴
                item.getAsString(text => {
                    document.execCommand('insertText', false, text);
                });
            }
        }
    });
}

window.initImageResizing = initImageResizing;
window.setupImageWrapper = setupImageWrapper;
window.convertToBlocks = convertToBlocks;
window.setupResizeHandlers = setupResizeHandlers;
window.setupPasteHandler = setupPasteHandler;
window.copyImageToClipboard = copyImageToClipboard;
window.duplicateImageBlock = duplicateImageBlock; 